<template>
  <div class="vulnerability-analysis-container">
    <el-card class="analysis-card">
      <template #header>
        <div class="card-header">
          <h2>漏洞聚合分析</h2>
          <el-button type="primary" @click="analyzeVulnerabilities" :loading="isAnalyzing">
            <el-icon><Refresh /></el-icon>
            开始分析
          </el-button>
        </div>
      </template>

      <!-- 分析配置区 -->
      <div class="analysis-config">
        <el-form :model="analysisForm" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="选择扫描任务">
                <el-select
                  v-model="analysisForm.scanIds"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择或输入扫描ID"
                  style="width: 100%"
                >
                  <el-option
                    v-for="scan in recentScans"
                    :key="scan.scan_id"
                    :label="`${scan.target} (${formatDate(scan.created_at)})`"
                    :value="scan.scan_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="analysisForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="分析维度">
                <el-select
                  v-model="analysisForm.dimensions"
                  multiple
                  placeholder="请选择分析维度"
                  style="width: 100%"
                >
                  <el-option label="漏洞类型分布" value="type" />
                  <el-option label="严重程度分布" value="severity" />
                  <el-option label="时间趋势分析" value="trend" />
                  <el-option label="组件影响分析" value="component" />
                  <el-option label="攻击路径关联" value="attack_path" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 加载状态 -->
      <div v-if="isAnalyzing" class="loading-container">
        <el-loading :fullscreen="false" text="正在进行漏洞聚合分析..." />
      </div>

      <!-- 分析结果区 -->
      <div v-else-if="analysisResults" class="analysis-results">
        <!-- 安全评分概览 -->
        <div class="security-overview">
          <div class="overview-card">
            <div class="score-circle" :class="securityScoreClass">
              <span class="score-value">{{ securityScore }}</span>
            </div>
            <div class="score-label">总体安全评分</div>
          </div>
          <div class="overview-stats">
            <div class="stat-item">
              <div class="stat-value">{{ totalVulnerabilities }}</div>
              <div class="stat-label">总漏洞数</div>
            </div>
            <div class="stat-item" :class="{ 'high-risk': highVulnerabilities > 0 }">
              <div class="stat-value">{{ highVulnerabilities }}</div>
              <div class="stat-label">高危漏洞</div>
            </div>
            <div class="stat-item" :class="{ 'medium-risk': mediumVulnerabilities > 0 }">
              <div class="stat-value">{{ mediumVulnerabilities }}</div>
              <div class="stat-label">中危漏洞</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ lowVulnerabilities }}</div>
              <div class="stat-label">低危漏洞</div>
            </div>
          </div>
        </div>

        <!-- 标签页切换 -->
        <el-tabs v-model="activeTab" type="card" class="analysis-tabs">
          <!-- 漏洞类型分布 -->
          <el-tab-pane label="漏洞类型分布" name="type">
            <div class="chart-container">
              <div class="chart" ref="typeDistributionChart"></div>
            </div>
            <div class="insights-container">
              <h3>类型分析洞察</h3>
              <el-timeline>
                <el-timeline-item
                  v-for="insight in typeInsights"
                  :key="insight.id"
                  :timestamp="''"
                >
                  <div class="insight-content">
                    <span class="insight-type" :class="insight.type">{{ insight.title }}</span>
                    <span class="insight-description">{{ insight.description }}</span>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-tab-pane>

          <!-- 严重程度分布 -->
          <el-tab-pane label="严重程度分布" name="severity">
            <div class="chart-container">
              <div class="chart" ref="severityDistributionChart"></div>
            </div>
            <div class="severity-details">
              <el-table :data="severityDetailsData" style="width: 100%">
                <el-table-column prop="severity" label="严重程度" width="120">
                  <template #default="scope">
                    <el-tag :type="getSeverityType(scope.row.severity)">{{ scope.row.severity }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="count" label="数量" width="80" />
                <el-table-column prop="percentage" label="占比" width="80">
                  <template #default="scope">
                    <span>{{ scope.row.percentage }}%</span>
                  </template>
                </el-table-column>
                <el-table-column prop="topTypes" label="主要类型">
                  <template #default="scope">
                    <el-tag 
                      v-for="type in scope.row.topTypes" 
                      :key="type"
                      size="small"
                      class="mr-2"
                    >
                      {{ getVulnerabilityTypeName(type) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>

          <!-- 时间趋势分析 -->
          <el-tab-pane label="时间趋势分析" name="trend">
            <div class="chart-container">
              <div class="chart" ref="trendChart"></div>
            </div>
            <div class="trend-insights">
              <h3>趋势分析</h3>
              <div class="insight-box" :class="overallTrend.class">
                <div class="insight-icon">
                  <el-icon :size="24">{{ overallTrend.icon }}</el-icon>
                </div>
                <div class="insight-content">
                  <h4>{{ overallTrend.title }}</h4>
                  <p>{{ overallTrend.description }}</p>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 组件影响分析 -->
          <el-tab-pane label="组件影响分析" name="component">
            <div class="chart-container">
              <div class="chart" ref="componentChart"></div>
            </div>
            <div class="component-details">
              <el-table :data="componentVulnerabilities" style="width: 100%">
                <el-table-column prop="component" label="组件" width="180" />
                <el-table-column prop="high" label="高危" width="80" />
                <el-table-column prop="medium" label="中危" width="80" />
                <el-table-column prop="low" label="低危" width="80" />
                <el-table-column prop="total" label="总计" width="80" />
                <el-table-column prop="riskScore" label="风险评分" width="100">
                  <template #default="scope">
                    <el-progress 
                      :percentage="scope.row.riskScore" 
                      :color="getRiskColor(scope.row.riskScore)"
                      :show-text="false"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>

          <!-- 攻击路径关联 -->
          <el-tab-pane label="攻击路径关联" name="attack_path">
            <div class="attack-path-container">
              <div class="chart" ref="attackPathChart"></div>
            </div>
            <div class="attack-path-insights">
              <h3>关键攻击路径</h3>
              <el-collapse v-model="activeAttackPaths">
                <el-collapse-item 
                  v-for="(path, index) in criticalAttackPaths" 
                  :key="index" 
                  :title="`路径 ${index + 1}: ${path.description}`"
                  :name="`path-${index}`"
                >
                  <div class="path-details">
                    <div class="path-steps">
                      <div 
                        v-for="(step, stepIndex) in path.steps" 
                        :key="stepIndex"
                        class="path-step"
                      >
                        <div class="step-number">{{ stepIndex + 1 }}</div>
                        <div class="step-content">
                          <div class="vulnerability-title">{{ step.vulnerability.title }}</div>
                          <div class="vulnerability-type">{{ getVulnerabilityTypeName(step.vulnerability.type) }}</div>
                          <div class="vulnerability-severity">
                            <el-tag :type="getSeverityType(step.vulnerability.severity)">
                              {{ step.vulnerability.severity }}
                            </el-tag>
                          </div>
                        </div>
                        <div v-if="stepIndex < path.steps.length - 1" class="step-arrow">
                          <el-icon><ArrowRight /></el-icon>
                        </div>
                      </div>
                    </div>
                    <div class="mitigation-recommendations">
                      <h4>缓解建议</h4>
                      <ul>
                        <li v-for="(recommendation, recIndex) in path.mitigationRecommendations" :key="recIndex">
                          {{ recommendation }}
                        </li>
                      </ul>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- 综合安全建议 -->
        <div class="security-recommendations">
          <h3>综合安全建议</h3>
          <div class="recommendations-grid">
            <el-card 
              v-for="recommendation in securityRecommendations" 
              :key="recommendation.id"
              class="recommendation-card"
              :class="`severity-${recommendation.severity}`"
            >
              <template #header>
                <div class="card-header">
                  <span class="recommendation-title">{{ recommendation.title }}</span>
                  <el-tag :type="getSeverityType(recommendation.severity)">
                    {{ recommendation.severity }}
                  </el-tag>
                </div>
              </template>
              <div class="recommendation-content">
                <p>{{ recommendation.description }}</p>
                <div class="recommendation-steps" v-if="recommendation.steps">
                  <h4>实施步骤：</h4>
                  <ol>
                    <li v-for="(step, index) in recommendation.steps" :key="index">
                      {{ step }}
                    </li>
                  </ol>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 无数据状态 -->
      <div v-else class="empty-state">
        <el-empty description="请配置并运行漏洞聚合分析" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, ArrowRight, Warning, Check, TrendingUp, TrendingDown, TrendingFlat } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import apiService from '../services/apiService.js'
import { formatDate } from '../utils/dateUtils.js'

// 响应式数据
const isAnalyzing = ref(false)
const analysisForm = ref({
  scanIds: [],
  dateRange: [],
  dimensions: ['type', 'severity', 'trend']
})
const recentScans = ref([])
const analysisResults = ref(null)
const activeTab = ref('type')
const activeAttackPaths = ref(['path-0'])

// 图表实例
let typeDistributionChart = null
let severityDistributionChart = null
let trendChart = null
let componentChart = null
let attackPathChart = null

// 计算属性
const securityScore = computed(() => {
  if (!analysisResults.value) return 0
  return analysisResults.value.securityScore?.toFixed(1) || 0
})

const securityScoreClass = computed(() => {
  const score = Number(securityScore.value)
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-medium'
  return 'score-poor'
})

const totalVulnerabilities = computed(() => {
  return analysisResults.value?.totalVulnerabilities || 0
})

const highVulnerabilities = computed(() => {
  return analysisResults.value?.severityCounts?.high || 0
})

const mediumVulnerabilities = computed(() => {
  return analysisResults.value?.severityCounts?.medium || 0
})

const lowVulnerabilities = computed(() => {
  return analysisResults.value?.severityCounts?.low || 0
})

const typeInsights = computed(() => {
  return analysisResults.value?.typeInsights || []
})

const severityDetailsData = computed(() => {
  if (!analysisResults.value) return []
  const { severityCounts } = analysisResults.value
  const total = totalVulnerabilities.value
  
  return [
    {
      severity: 'high',
      count: severityCounts.high,
      percentage: total > 0 ? ((severityCounts.high / total) * 100).toFixed(1) : 0,
      topTypes: analysisResults.value.highSeverityTopTypes || []
    },
    {
      severity: 'medium',
      count: severityCounts.medium,
      percentage: total > 0 ? ((severityCounts.medium / total) * 100).toFixed(1) : 0,
      topTypes: analysisResults.value.mediumSeverityTopTypes || []
    },
    {
      severity: 'low',
      count: severityCounts.low,
      percentage: total > 0 ? ((severityCounts.low / total) * 100).toFixed(1) : 0,
      topTypes: analysisResults.value.lowSeverityTopTypes || []
    }
  ].filter(item => item.count > 0)
})

const overallTrend = computed(() => {
  if (!analysisResults.value?.trendAnalysis) {
    return {
      class: 'neutral',
      icon: TrendingFlat,
      title: '暂无趋势数据',
      description: '需要多次扫描结果才能进行趋势分析'
    }
  }
  
  const { trendAnalysis } = analysisResults.value
  if (trendAnalysis.overallTrend === 'improving') {
    return {
      class: 'improving',
      icon: TrendingDown,
      title: '安全状况改善',
      description: `漏洞数量减少了${trendAnalysis.changePercentage}%，安全评分提升了${trendAnalysis.scoreImprovement}分`
    }
  } else if (trendAnalysis.overallTrend === 'worsening') {
    return {
      class: 'worsening',
      icon: TrendingUp,
      title: '安全状况恶化',
      description: `漏洞数量增加了${Math.abs(trendAnalysis.changePercentage)}%，安全评分下降了${Math.abs(trendAnalysis.scoreImprovement)}分`
    }
  } else {
    return {
      class: 'stable',
      icon: TrendingFlat,
      title: '安全状况稳定',
      description: '漏洞数量和安全评分相对稳定，建议持续监控'
    }
  }
})

const componentVulnerabilities = computed(() => {
  return analysisResults.value?.componentVulnerabilities || []
})

const criticalAttackPaths = computed(() => {
  return analysisResults.value?.criticalAttackPaths || []
})

const securityRecommendations = computed(() => {
  return analysisResults.value?.securityRecommendations || []
})

// 方法
const loadRecentScans = async () => {
  try {
    const response = await apiService.getScanHistory()
    recentScans.value = response.slice(0, 10) // 只显示最近10次扫描
  } catch (error) {
    console.error('加载扫描历史失败:', error)
    ElMessage.error('加载扫描历史失败')
  }
}

const analyzeVulnerabilities = async () => {
  // 验证表单
  if (analysisForm.value.scanIds.length === 0 && analysisForm.value.dateRange.length === 0) {
    ElMessage.warning('请选择扫描任务或时间范围')
    return
  }
  
  isAnalyzing.value = true
  
  try {
    // 调用分析API
    const response = await apiService.analyzeVulnerabilities(analysisForm.value)
    analysisResults.value = response
    
    // 初始化图表
    setTimeout(() => {
      initCharts()
    }, 100)
    
    ElMessage.success('漏洞聚合分析完成')
  } catch (error) {
    console.error('漏洞分析失败:', error)
    ElMessage.error('漏洞分析失败，请重试')
  } finally {
    isAnalyzing.value = false
  }
}

const initCharts = () => {
  // 初始化各维度图表
  if (analysisForm.value.dimensions.includes('type')) {
    initTypeDistributionChart()
  }
  
  if (analysisForm.value.dimensions.includes('severity')) {
    initSeverityDistributionChart()
  }
  
  if (analysisForm.value.dimensions.includes('trend')) {
    initTrendChart()
  }
  
  if (analysisForm.value.dimensions.includes('component')) {
    initComponentChart()
  }
  
  if (analysisForm.value.dimensions.includes('attack_path')) {
    initAttackPathChart()
  }
}

const initTypeDistributionChart = () => {
  const chartDom = document.querySelector('.vulnerability-analysis-container .analysis-results .analysis-tabs [name="type"] .chart')
  if (!chartDom) return
  
  if (typeDistributionChart) {
    typeDistributionChart.dispose()
  }
  
  typeDistributionChart = echarts.init(chartDom)
  
  const option = {
    title: {
      text: '漏洞类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '漏洞类型',
        type: 'pie',
        radius: '50%',
        data: analysisResults.value.typeDistribution.map(item => ({
          value: item.count,
          name: getVulnerabilityTypeName(item.type)
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  typeDistributionChart.setOption(option)
}

const initSeverityDistributionChart = () => {
  const chartDom = document.querySelector('.vulnerability-analysis-container .analysis-results .analysis-tabs [name="severity"] .chart')
  if (!chartDom) return
  
  if (severityDistributionChart) {
    severityDistributionChart.dispose()
  }
  
  severityDistributionChart = echarts.init(chartDom)
  
  const option = {
    title: {
      text: '严重程度分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['高危', '中危', '低危']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [
          {
            value: highVulnerabilities.value,
            itemStyle: { color: '#f56c6c' }
          },
          {
            value: mediumVulnerabilities.value,
            itemStyle: { color: '#e6a23c' }
          },
          {
            value: lowVulnerabilities.value,
            itemStyle: { color: '#67c23a' }
          }
        ],
        type: 'bar'
      }
    ]
  }
  
  severityDistributionChart.setOption(option)
}

const initTrendChart = () => {
  const chartDom = document.querySelector('.vulnerability-analysis-container .analysis-results .analysis-tabs [name="trend"] .chart')
  if (!chartDom) return
  
  if (!analysisResults.value?.trendAnalysis?.dates) return
  
  if (trendChart) {
    trendChart.dispose()
  }
  
  trendChart = echarts.init(chartDom)
  
  const option = {
    title: {
      text: '漏洞数量趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['高危', '中危', '低危', '总计'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: analysisResults.value.trendAnalysis.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '高危',
        type: 'line',
        stack: '总量',
        data: analysisResults.value.trendAnalysis.highTrend,
        itemStyle: { color: '#f56c6c' }
      },
      {
        name: '中危',
        type: 'line',
        stack: '总量',
        data: analysisResults.value.trendAnalysis.mediumTrend,
        itemStyle: { color: '#e6a23c' }
      },
      {
        name: '低危',
        type: 'line',
        stack: '总量',
        data: analysisResults.value.trendAnalysis.lowTrend,
        itemStyle: { color: '#67c23a' }
      },
      {
        name: '总计',
        type: 'line',
        data: analysisResults.value.trendAnalysis.totalTrend,
        itemStyle: { color: '#409eff' },
        emphasis: {
          focus: 'series'
        }
      }
    ]
  }
  
  trendChart.setOption(option)
}

const initComponentChart = () => {
  const chartDom = document.querySelector('.vulnerability-analysis-container .analysis-results .analysis-tabs [name="component"] .chart')
  if (!chartDom) return
  
  if (componentChart) {
    componentChart.dispose()
  }
  
  componentChart = echarts.init(chartDom)
  
  const components = componentVulnerabilities.value.map(item => item.component)
  const highData = componentVulnerabilities.value.map(item => item.high)
  const mediumData = componentVulnerabilities.value.map(item => item.medium)
  const lowData = componentVulnerabilities.value.map(item => item.low)
  
  const option = {
    title: {
      text: '组件漏洞分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['高危', '中危', '低危'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: components,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '高危',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: highData,
        itemStyle: { color: '#f56c6c' }
      },
      {
        name: '中危',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: mediumData,
        itemStyle: { color: '#e6a23c' }
      },
      {
        name: '低危',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: lowData,
        itemStyle: { color: '#67c23a' }
      }
    ]
  }
  
  componentChart.setOption(option)
}

const initAttackPathChart = () => {
  const chartDom = document.querySelector('.vulnerability-analysis-container .analysis-results .analysis-tabs [name="attack_path"] .chart')
  if (!chartDom) return
  
  if (attackPathChart) {
    attackPathChart.dispose()
  }
  
  attackPathChart = echarts.init(chartDom)
  
  // 构建攻击路径的关系图数据
  const nodes = []
  const links = []
  const nodeMap = new Map()
  
  // 为每条攻击路径添加节点和链接
  criticalAttackPaths.value.forEach(path => {
    path.steps.forEach((step, index) => {
      const nodeId = `vuln-${step.vulnerability.id}`
      if (!nodeMap.has(nodeId)) {
        nodeMap.set(nodeId, nodes.length)
        nodes.push({
          id: nodeId,
          name: step.vulnerability.title,
          symbolSize: getSeveritySize(step.vulnerability.severity),
          itemStyle: {
            color: getSeverityColor(step.vulnerability.severity)
          },
          value: step.vulnerability.severity,
          category: step.vulnerability.type
        })
      }
      
      // 添加链接
      if (index > 0) {
        const prevNodeId = `vuln-${path.steps[index - 1].vulnerability.id}`
        links.push({
          source: prevNodeId,
          target: nodeId
        })
      }
    })
  })
  
  const option = {
    title: {
      text: '攻击路径关联图',
      left: 'center'
    },
    tooltip: {},
    legend: [
      {
        data: [...new Set(nodes.map(node => node.category))],
        bottom: 0
      }
    ],
    animationDurationUpdate: 1500,
    animationEasingUpdate: 'quinticInOut',
    series: [
      {
        type: 'graph',
        layout: 'force',
        force: {
          repulsion: 1000,
          edgeLength: 150
        },
        roam: true,
        label: {
          show: true,
          formatter: '{b}'
        },
        data: nodes,
        links: links,
        lineStyle: {
          opacity: 0.9,
          width: 2,
          curveness: 0
        }
      }
    ]
  }
  
  attackPathChart.setOption(option)
}

// 辅助函数
const getVulnerabilityTypeName = (type) => {
  const typeMap = {
    'sql_injection': 'SQL注入',
    'xss': '跨站脚本',
    'info_leak': '信息泄露',
    'csrf': 'CSRF攻击',
    'cmd_injection': '命令注入',
    'file_upload': '文件上传',
    'auth_bypass': '认证绕过',
    'ssrf': '服务器请求伪造',
    'lfi': '本地文件包含',
    'rce': '远程代码执行',
    'path_traversal': '路径遍历',
    'insecure_config': '不安全配置',
    'cors_misconfiguration': 'CORS配置错误',
    'ssl_tls_issues': 'SSL/TLS问题',
    'weak_password': '弱密码',
    'subdomain_takeover': '子域名接管',
    'other': '其他漏洞'
  }
  return typeMap[type] || type
}

const getSeverityType = (severity) => {
  const typeMap = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'success'
  }
  return typeMap[severity] || 'info'
}

const getSeverityColor = (severity) => {
  const colorMap = {
    'high': '#f56c6c',
    'medium': '#e6a23c',
    'low': '#67c23a'
  }
  return colorMap[severity] || '#909399'
}

const getSeveritySize = (severity) => {
  const sizeMap = {
    'high': 60,
    'medium': 40,
    'low': 30
  }
  return sizeMap[severity] || 20
}

const getRiskColor = (score) => {
  if (score >= 80) return '#f56c6c'
  if (score >= 60) return '#e6a23c'
  return '#67c23a'
}

// 监听标签页变化，初始化对应图表
watch(activeTab, (newTab) => {
  if (!analysisResults.value) return
  
  setTimeout(() => {
    if (newTab === 'type' && analysisForm.value.dimensions.includes('type')) {
      initTypeDistributionChart()
    } else if (newTab === 'severity' && analysisForm.value.dimensions.includes('severity')) {
      initSeverityDistributionChart()
    } else if (newTab === 'trend' && analysisForm.value.dimensions.includes('trend')) {
      initTrendChart()
    } else if (newTab === 'component' && analysisForm.value.dimensions.includes('component')) {
      initComponentChart()
    } else if (newTab === 'attack_path' && analysisForm.value.dimensions.includes('attack_path')) {
      initAttackPathChart()
    }
  }, 100)
})

// 组件挂载时加载最近扫描历史
onMounted(() => {
  loadRecentScans()
})
</script>

<style scoped>
.vulnerability-analysis-container {
  padding: 20px;
}

.analysis-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.analysis-config {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.analysis-results {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.security-overview {
  display: flex;
  margin-bottom: 30px;
  gap: 20px;
}

.overview-card {
  flex: 0 0 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.score-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.score-circle.score-good {
  background-color: #67c23a;
  color: white;
}

.score-circle.score-medium {
  background-color: #e6a23c;
  color: white;
}

.score-circle.score-poor {
  background-color: #f56c6c;
  color: white;
}

.score-value {
  font-size: 36px;
  font-weight: bold;
}

.score-label {
  font-size: 16px;
  color: #606266;
}

.overview-stats {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
  align-items: center;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-item.high-risk {
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
}

.stat-item.medium-risk {
  background-color: #fdf6ec;
  border: 1px solid #fde2e2;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 4px;
}

.analysis-tabs {
  margin-bottom: 30px;
}

.chart-container {
  height: 400px;
  margin-bottom: 20px;
}

.chart {
  width: 100%;
  height: 100%;
}

.insights-container {
  margin-top: 20px;
}

.insight-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.insight-type {
  font-weight: bold;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.insight-type.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.insight-type.success {
  background-color: #f0f9eb;
  color: #67c23a;
}

.insight-type.danger {
  background-color: #fef0f0;
  color: #f56c6c;
}

.insight-description {
  flex: 1;
  color: #606266;
}

.severity-details,
.component-details {
  margin-top: 20px;
}

.trend-insights {
  margin-top: 20px;
}

.insight-box {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.insight-box.improving {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
}

.insight-box.worsening {
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
}

.insight-box.stable {
  background-color: #f4f4f5;
  border: 1px solid #e9e9eb;
}

.insight-icon {
  margin-top: 4px;
}

.insight-box.improving .insight-icon {
  color: #67c23a;
}

.insight-box.worsening .insight-icon {
  color: #f56c6c;
}

.insight-box.stable .insight-icon {
  color: #909399;
}

.insight-box h4 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
}

.insight-box p {
  margin: 0;
  color: #606266;
}

.attack-path-container {
  height: 500px;
  margin-bottom: 20px;
}

.attack-path-insights {
  margin-top: 20px;
}

.path-details {
  padding: 16px;
}

.path-steps {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.path-step {
  display: flex;
  align-items: center;
  gap: 12px;
}

.step-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.vulnerability-title {
  font-weight: 600;
  margin-bottom: 4px;
}

.vulnerability-type {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.step-arrow {
  color: #909399;
}

.mitigation-recommendations {
  background-color: #f0f9ff;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.mitigation-recommendations h4 {
  margin: 0 0 12px 0;
  color: #409eff;
}

.mitigation-recommendations ul {
  margin: 0;
  padding-left: 20px;
}

.mitigation-recommendations li {
  margin-bottom: 8px;
  color: #606266;
}

.mitigation-recommendations li:last-child {
  margin-bottom: 0;
}

.security-recommendations {
  margin-top: 40px;
}

.security-recommendations h3 {
  margin-bottom: 20px;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.recommendation-card {
  transition: all 0.3s ease;
}

.recommendation-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.recommendation-card.severity-high {
  border-left: 4px solid #f56c6c;
}

.recommendation-card.severity-medium {
  border-left: 4px solid #e6a23c;
}

.recommendation-card.severity-low {
  border-left: 4px solid #67c23a;
}

.recommendation-content {
  line-height: 1.6;
  color: #606266;
}

.recommendation-content h4 {
  margin-top: 16px;
  margin-bottom: 8px;
  color: #303133;
  font-size: 16px;
}

.recommendation-steps ol {
  margin: 0;
  padding-left: 20px;
}

.recommendation-steps li {
  margin-bottom: 8px;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .vulnerability-analysis-container {
    padding: 10px;
  }
  
  .security-overview {
    flex-direction: column;
  }
  
  .overview-card {
    flex: auto;
    width: 100%;
  }
  
  .recommendations-grid {
    grid-template-columns: 1fr;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .attack-path-container {
    height: 400px;
  }
}
</style>